package com.example.snow

import android.content.Context
import android.util.AttributeSet
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.webkit.WebView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout

class ScrollAwareWebView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : WebView(context, attrs, defStyleAttr) {

    private var swipeRefreshLayout: SwipeRefreshLayout? = null

    fun setSwipeRefreshLayout(layout: SwipeRefreshLayout) {
        this.swipeRefreshLayout = layout
        updateSwipeRefreshState()
    }

    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        super.onScrollChanged(l, t, oldl, oldt)
        updateSwipeRefreshState()
    }

    private fun updateSwipeRefreshState() {
        swipeRefreshLayout?.isEnabled = isAtTop()
    }

    private fun isAtTop(): Boolean {
        return scrollY == 0
    }

    override fun onCheckIsTextEditor(): Boolean {
        // 确保WebView被识别为文本编辑器
        return true
    }

    override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
        val inputConnection = super.onCreateInputConnection(outAttrs)
        // 设置输入类型，确保输入法正常工作
        outAttrs.imeOptions = outAttrs.imeOptions or EditorInfo.IME_FLAG_NO_EXTRACT_UI
        outAttrs.inputType = EditorInfo.TYPE_CLASS_TEXT
        return inputConnection
    }

}